# encoding: utf-8

class CommentsWorker < ApplicationWorker

  def perform(ph_id, comment, search_type)
    Sidekiq.redis do |redis|
      begin
        return redis.del("flowy:create_commen:#{search_type}:#{ph_id}") unless rec = redis.rpop("flowy:create_comment:#{search_type}:#{ph_id}")
        return redis.del("flowy:create_comment:#{search_type}:#{ph_id}") unless push_history = PushHistory.where(:_id => ph_id).first

        for_t = JSON.parse(rec)
        tracked_comment = comment

        while Statistics::Tweet.success.where(:wid => for_t["wid"]).first
          logger.info "发送状态:> 已经发送过了"
          return redis.del("flowy:create_commen:#{search_type}:#{ph_id}") unless rec = redis.rpop("flowy:create_comment:#{search_type}:#{ph_id}")
          return redis.del("flowy:create_comment:#{search_type}:#{ph_id}") unless push_history = PushHistory.where(:_id => ph_id).first
          for_t     = JSON.parse(rec)
          next unless for_t["wid"]
        end
        return unless for_t["wid"]
        task      = push_history.task

        if for_t['retweet']
          if tweet = Statistics::Tweet.where('_id' => for_t['_id']).first
            push_history = tweet.push_history
            push_history.new_tweet(tweet.wid)
            comment = push_history.comment
          else
            redis.del("flowy:create_comment:#{search_type}:#{ph_id}")
            return
          end
        end
        tweet = push_history.new_tweet(for_t["wid"])
        url   = comment.match(/(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix).to_s.gsub('', '')
        logger.info ">发送准备: 检测url:#{url}"
        if url.present?
          tracked_comment = comment.gsub(url, tweet.set_track_url(url))
          logger.info ">发送准备: 过滤url:#{tweet.track_url}"
        else
          tracked_comment = comment
        end
        result        = task.account.send("create_comment_#{search_type.downcase}", tracked_comment, for_t["wid"], for_t["uid"])
        # 这里需要加入错误处理
        result['wid'] = for_t["wid"]
        push_history.add_tweet result, for_t
      rescue
        tweet.destroy
        p result
        logger.info ">发生错误: 紧急处理"
      end

      if redis.llen("flowy:create_comment:#{search_type}:#{ph_id}") > 0
        CommentsWorker.perform_at(Utility::BlockHacker.polling_gap(search_type, :create_comment),
                                  ph_id,
                                  comment,
                                  search_type)
      else
        task.refresh_tweets_location
        task.get_summary(:make_now)
        redis.del("flowy:create_comment:#{search_type}:#{ph_id}")
      end
    end
    # do something
  end


end
